// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <melon/benchmark.h>
#include <melon/init/init.h>
#include <pollux/functions/registerer.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>
#include <pollux/vector/vector_fuzzer.h>
#include <pollux/testing/vector/vector_test_base.h>

using namespace kumo::pollux;
using namespace kumo::pollux::exec;

namespace {

class MapBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  MapBenchmark() {
    functions::prestosql::registerAllScalarFunctions();

    VectorFuzzer::Options options;
    options.vectorSize = 10'000;

    VectorFuzzer fuzzer(options, pool());

    // Generate flat vectors to use as keys and values for the map.
    data_ = std::dynamic_pointer_cast<RowVector>(fuzzer.fuzzFlat(
        ROW({"k0", "k1", "k2", "v0", "v1", "v2"},
            {BIGINT(), BIGINT(), BIGINT(), BIGINT(), BIGINT(), BIGINT()})));
  }

  size_t runConstantKeys(size_t times) {
    return run(
        "map(array_constructor(35, 2, 101), array_constructor(v0, v1, v2))",
        times);
  }

  size_t runFlatKeys(size_t times) {
    return run(
        "map(array_constructor(k0, k1, k2), array_constructor(v0, v1, v2))",
        times);
  }

 private:
  size_t run(const std::string& expression, size_t times) {
    melon::BenchmarkSuspender suspender;
    auto exprSet = compileExpression(expression, as_row_type(data_->type()));
    suspender.dismiss();

    int cnt = 0;
    for (auto i = 0; i < times * 1'000; i++) {
      cnt += evaluate(exprSet, data_)->size();
    }
    return cnt;
  }

  RowVectorPtr data_;
};

BENCHMARK_MULTI(constantKeys, n) {
  MapBenchmark benchmark;
  return benchmark.runConstantKeys(n);
}

BENCHMARK_MULTI(flatKeys, n) {
  MapBenchmark benchmark;
  return benchmark.runFlatKeys(n);
}

} // namespace

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};
  melon::runBenchmarks();
  return 0;
}
